package org.example.subside.Play.ReadLocalFile;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;


import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Word 操作工具类
 */
@Slf4j
public class WordUtil {
    // 定义静态的文件后缀
    public static final String SUFFIX_DOC = ".doc";
    public static final String SUFFIX_DOCX = ".docx";

    /**
     * 读取 Word 入口方法，根据后缀，调用方法
     *
     * @param suffix   文件后缀
     * @param filePath 文件路径
     * @return
     */
    public static String readWord(String suffix, String filePath) {
        String wordStr = "";
        try (InputStream input = new FileInputStream(filePath)) {
            // docx 类型
            if (SUFFIX_DOCX.equals(suffix)) {
                wordStr = readDocx(input);
                // doc 类型
            } else if (SUFFIX_DOC.equals(suffix)) {
                wordStr = readDoc(input);
            }
        } catch (Exception e) {
            log.error("readWord [{}] is error", filePath);
        }
        wordStr = wordStr.replace("\n", "");
        wordStr = wordStr.replace("\\\\r", "");
        wordStr = wordStr.replace("\\\\t", "");
        return wordStr;
    }

    /**
     * 读取 doc 类型，使用 WordExtractor 对象，传递输入流
     *
     * @param inputStream
     * @return
     */
    private static String readDoc(InputStream inputStream) {
        try {
            String content = "";
            WordExtractor ex = new WordExtractor(inputStream);
            content = ex.getText();
            ex.close();
            return content;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 读取 docx 类型，使用 XWPFDocument 对象，传递输入流
     *
     * @param inputStream
     * @return
     */
    private static String readDocx(InputStream inputStream) {
        try {
            String content = "";
            XWPFDocument xdoc = new XWPFDocument(inputStream);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            content = extractor.getText();
            extractor.close();
            return content;
        } catch (Exception e) {
            return null;
        }
    }
}
